package com.atguigu.guli.serviceedu.controller;


import com.atguigu.commonutils.utils.JwtUtil;
import com.atguigu.guli.serviceedu.entity.Comment;
import com.atguigu.guli.serviceedu.service.CommentService;
import com.atguigu.servicebase.exception.Assert;
import com.atguigu.servicebase.result.R;
import com.atguigu.servicebase.result.ResponseEnum;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 评论 前端控制器
 * </p>
 *
 * @author atguigu
 * @since 2021-08-07
 */
@Api(tags = "前台评论查询")
@CrossOrigin
@RestController
@RequestMapping("/edu/comment")
public class CommentApiController {

    @Autowired
    private CommentService commentService;

    //根据课程id查询评论列表
    @ApiOperation(value = "评论分页列表")
    @GetMapping("{page}/{limit}")
    public R index(
            @ApiParam(name = "page", value = "当前页码", required = true, example = "1")
            @PathVariable Long page,
            @ApiParam(name = "limit", value = "每页记录数", required = true, example = "8")
            @PathVariable Long limit,
            @ApiParam(name = "courseQuery", value = "查询对象", required = false)
            String courseId) {
        Page<Comment> pageParam = new Page<>(page, limit);
        QueryWrapper<Comment> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);

        commentService.page(pageParam,wrapper);

        Map<String, Object> map = new HashMap<>();
        map.put("items", pageParam.getRecords());
        map.put("current", pageParam.getCurrent());
        map.put("pages", pageParam.getPages());
        map.put("size", pageParam.getSize());
        map.put("total", pageParam.getTotal());
        map.put("hasNext", pageParam.hasNext());
        map.put("hasPrevious", pageParam.hasPrevious());
        return R.ok().data(map);
    }

    @ApiOperation(value = "添加评论")
    @PostMapping("auth/save")
    public R save(@RequestBody Comment comment, HttpServletRequest request) {
        String memberId = JwtUtil.getMemberIdByJwtToken(request);
        Assert.notEmpty(memberId, ResponseEnum.LAND_EXPIRATION);
        String nickname = JwtUtil.getMemberNicknameByJwtToken(request);
        comment.setNickname(nickname);

        commentService.save(comment);
        return R.ok();
    }
}

